/**
 *
 * Project: news
 * Filename: FckXml.java
 * Author: hongliang
 * Created Date: 2005-10-10
 *
 */

package com.deity.news.action;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import com.opensymphony.webwork.ServletActionContext;
import com.deity.news.util.MyActionSupport;
import com.deity.news.util.UserRoleUtil;

public class Template extends MyActionSupport {

	private String content;

	private String filepath;

	public String execute() {
		if (UserRoleUtil.isAdmin(getUsername()) == false) {
			return NONE;
		}

		filepath = ServletActionContext.getServletContext().getRealPath(
				"/fckeditor/fcktemplates.xml");

		if (content == null) {
			read();
			return INPUT;
		}

		write();

		return SUCCESS;
	}

	public String getContent() {
		return content;
	}

	private void read() {
		StringBuffer sb = new StringBuffer();

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(new FileInputStream(
					filepath)));

			String line = in.readLine();
			while (line != null) {
				sb.append(line);
				sb.append('\n');
				line = in.readLine();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}

		content = sb.toString();
	}

	public void setContent(String content) {
		this.content = content;
	}

	private void write() {
		PrintWriter pw;
		try {
			pw = new PrintWriter(new FileOutputStream(filepath));
			pw.write(content);
			pw.close();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
